const authApi = require('../../../api/auth')
const app = getApp()

Page({
  data: {
    username: '',
    password: '',
    showPassword: false,
    isFormValid: false
  },

  onLoad: function (options) {
    // 检查是否已经登录
    if (app.globalData.isLogin) {
      this.redirectToHome()
    }
  },

  // 用户名输入事件
  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
    this.checkFormValid()
  },

  // 密码输入事件
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
    this.checkFormValid()
  },

  // 切换密码显示状态
  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    })
  },

  // 检查表单是否有效
  checkFormValid() {
    const { username, password } = this.data
    const isValid = username.trim().length > 0 && password.trim().length > 0
    this.setData({
      isFormValid: isValid
    })
  },

  // 处理登录
  async handleLogin() {
    if (!this.data.isFormValid) {
      return
    }

    const { username, password } = this.data

    try {
      const result = await authApi.login({
        username: username.trim(),
        password: password.trim()
      })

      // 登录成功，保存用户信息和token
      app.setLoginStatus(result.userInfo, result.token)

      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })

      // 延迟跳转到首页
      setTimeout(() => {
        this.redirectToHome()
      }, 1500)

    } catch (error) {
      console.error('登录失败:', error)
      wx.showToast({
        title: error.message || '登录失败',
        icon: 'none'
      })
    }
  },



  // 跳转到注册页面
  goToRegister() {
    wx.navigateTo({
      url: '/pages/auth/register/register'
    })
  },



  // 跳转到首页
  redirectToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
}) 